<?php

require_once __DIR__ . '/ControllerACL.php';
require_once '../Models/Model.php';

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ControllerAbstract
 *
 * @author david
 */
abstract class ControllerAbstract extends Model {

    protected $useLayout = true;
    protected $config = null;
    protected $get = [];

    abstract public function principal();

    public function __construct($config) {
        $this->config = $config;

        //Ajax nao usa layout
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            $this->useLayout = false;
        }

        $this->defineGET();
    }

    public function renderMenu() {
        include __DIR__ . '/views/layout/menu.php';
    }

    public function renderLayoutScripts() {
        $html = '';
        try {
            if ($this->config && isset($this->config['layout'])) {
                //CSS da config
                if (isset($this->config['layout']['css']) && !empty($this->config['layout']['css'])) {
                    foreach ($this->config['layout']['css'] as $css) {
                        $html .= "<link rel='stylesheet' type='text/css' href='" . $css . "'>" . "\n";
                    }
                }

                //js da config
                if (isset($this->config['layout']['js']) && !empty($this->config['layout']['js'])) {
                    foreach ($this->config['layout']['js'] as $js) {
                        $html .= "<script src='" . $js . "' type='text/javascript'></script>" . "\n";
                    }
                }
            }
        } catch (Exception $exc) {
            
        }
        return $html;
    }

    /**
     * Renderiza a view
     * 
     * @param string $viewName O nome da view a ser renderizada
     * @param array|object $data
     */
    public function render($viewName, $data = null) {
        ob_start();

        $this->controllerACL = new ControllerACL($this->config);

        // carrega a view para colocar na variavel content
        include __DIR__ . '/views/' . $viewName . '.php';

        $content = ob_get_clean();

        if ($this->useLayout) {
            include __DIR__ . '/views/layout.php';
        } else {
            echo $content;
        }

        die();
    }

    public function renderView($viewName) {
        include __DIR__ . '/views/' . $viewName . '.php';
    }

    public function renderJson($data) {
        echo json_encode($data);
    }

    public function persistence() {
        if (isset($_POST["data"])) {

            // define a entidade desejada para a realizaçao da _action
            $class = array_keys($_POST["data"])[0];

            // valores da entidade para a action
            $objeto = $_POST["data"][$class];
            $success = $this->persiste($class, $objeto);

            if ($success != "erro") {
                $result = '{data:{success: true, ' . json_encode($success) . '}}';
            }
        } else {
            $result = '{data:{success: false, "Erro nos atributos"}}';
        }
        echo $result;
    }

    public function persiste($objeto) {

        $class = get_class($objeto);
        
        // define o local da entidade
        $arquivoEntidade = ".." . DS . 'entity' . DS . $class . ".php";
        
        if (file_exists($arquivoEntidade)) {
            include_once $arquivoEntidade;

            if (class_exists($class)) {
                if (!property_exists($objeto, "action")) {
                    $objeto->action = "list";
                }

                $model = new Model();
                $success = $model->persistir($class, $objeto);
            } else {
                $success = "404 - Classe nao existe!";
            }
        } else {
            $success = "404 - Pagina nao encontrada!";
        }

        return $success;
    }

    public function defineGET() {
        // valores do GET
        $gets = explode("?", $_SERVER["REQUEST_URI"]);
        if (isset($gets[1])) {
            $gets = explode("&", $gets[1]);
            foreach ($gets as $row) {
                $rowAux = explode("=", $row);
                $this->get[$rowAux[0]] = $rowAux[1];
            }
        }
    }

}